package com.zwcloud.zw.railway.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zwcloud.zw.railway.entity.*;
import com.zwcloud.zw.railway.mapper.CcxxallMapper;
import com.zwcloud.zw.railway.mapper.DataUploadLogMapper;
import com.zwcloud.zw.railway.mapper.TrainInfoMapper;
import com.zwcloud.zw.railway.repository.TrainRepository;
import com.zwcloud.zw.railway.service.TrainService;
import com.zwcloud.zw.railway.utils.DestinationInitializer;
import com.zwcloud.zw.railway.utils.HttpUtils;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class TrainServiceImpl implements TrainService {

    private static final Logger log = LoggerFactory.getLogger(TrainServiceImpl.class);

    @Resource
    private TrainRepository trainRepository;

    @Resource
    private HttpUtils httpUtils;

    @Resource
    private DataUploadLogMapper dataUploadLogMapper;

    @Resource
    private CcxxallMapper ccxxallMapper;

    @Resource
    private TrainInfoMapper trainInfoMapper;

/*    private static final String ADD_FREIGHT_YARD_URL = "http://120.71.225.100:8866/railway/dest/addFreightYardDivision";
    private static final String RAILWAY_API_URL = "http://120.71.225.100:8866/railway/api/railway/receiveRailwayAndDetailsInfo";*/


    //测试内网
    private static final String ADD_FREIGHT_YARD_URL = "http://172.16.4.55:9999/railway/dest/addFreightYardDivision";
    private static final String RAILWAY_API_URL = "http://172.16.4.55:9999/railway/api/railway/receiveRailwayAndDetailsInfo";
    private static final String ACCESS_CODE = "sRrWpAF3Da42GuQVuzgICA==";

    // 计算昨天的日期，返回格式为 yyyyMMdd（例如 20241031）
    private String getYesterdayDate() {
        LocalDate yesterday = LocalDate.now().minusDays(1);
        return yesterday.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
    }

    // 调用运往地 API，上传 cpxxall 表中昨天以后的铁路平台名称
    @Override
    public ResponseEntity<String> callAddFreightYardApi() {
        String yesterday = getYesterdayDate();
        List<String> railwayPlatformNames = Optional.ofNullable(trainRepository.getNewRailwayPlatformNames(yesterday))
                .orElse(Collections.emptyList());

        if (!railwayPlatformNames.isEmpty()) {
            for (String railwayPlatformName : railwayPlatformNames) {
                List<Long> cpxxKeys = Optional.ofNullable(getCpxxKeysFromPlatformName(railwayPlatformName))
                        .orElse(Collections.emptyList());

                String interfaceType = "addFreightYardDivision";

                for (Long cpxxKey : cpxxKeys) {
                    if (cpxxKey == null) {
                        System.out.println("cpxxKey 为空，跳过此条数据。");
                        continue;
                    }

                    if (checkIfUploaded(cpxxKey, interfaceType)) {
                        System.out.println("运往地数据已上传，跳过此条数据。");
                        continue;
                    }

                    String requestBody = buildRequestBody(railwayPlatformName);
                    if (requestBody == null || requestBody.trim().isEmpty()) {
                        System.out.println("请求体为空，跳过此请求。");
                        continue;
                    }

                    ResponseEntity<String> response = httpUtils.sendPostRequest(ADD_FREIGHT_YARD_URL, requestBody, ACCESS_CODE);
                    System.out.println("响应状态: " + response.getStatusCode());
                    System.out.println("响应体: " + response.getBody());

                    recordUploadLog(cpxxKey, response.getStatusCode().is2xxSuccessful() ? "ok" : "error",
                            response.getStatusCodeValue(), response.getBody(), interfaceType);
                }
            }
        }
        return ResponseEntity.ok("API调用完成！");
    }

    // 检查新数据并调用运往地 API
    @Override
    public void checkForNewDataAndCallApi() {
        callAddFreightYardApi();
    }

    // 检查并上传 ccxxall 表中昨天以后的数据
    @Override
    public void checkFoDataAndCallApi() {
        try {
            //String yesterday = String.valueOf(20240901);
            String yesterday = getYesterdayDate();
            // 获取 ccxxall 表中昨天以后的数据
            List<CcxxallEntity> ccxxallList = ccxxallMapper.selectList(
                    new QueryWrapper<CcxxallEntity>().ge("ccxx_dateend", yesterday)
            );

            for (CcxxallEntity ccxxall : ccxxallList) {
                Integer ccxxKey = ccxxall.getCcxxKey();
                // 根据 ccxx_key 查询对应的 cpxx_key
                String ccxxPici = ccxxall.getCcxxPici();

                TrainInfo cpxxall = trainInfoMapper.selectOne(
                        new QueryWrapper<TrainInfo>().eq("cpxx_pici", ccxxPici).last("LIMIT 1")
                );
                if (cpxxall == null) {
                    System.out.println("未找到对应的 cpxx_key，跳过此条数据。ccxx_key: " + ccxxKey);
                    continue;
                }
                String interfaceType = "receiveRailwayAndDetailsInfo";
                long cpxxKey = cpxxall.getCpxxKey().longValue();

                if (checkIfUploaded(cpxxKey, interfaceType)) {
                    System.out.println("TrainInfo 数据已上传，跳过此条数据。cpxx_key: " + cpxxKey);
                    continue;
                }
                System.out.println("准备上传数据: ccxx_key=" + ccxxKey + ", ccxx_pici=" + ccxxall.getCcxxPici() + ", ccxx_checi=" + ccxxall.getCcxxCheci());
                log.info("准备上传数据: ccxx_key=" + ccxxKey + ", ccxx_pici=" + ccxxall.getCcxxPici() + ", ccxx_checi=" + ccxxall.getCcxxCheci());
                // 构建请求体
                String requestBody = buildRequestBody(ccxxall, cpxxall, interfaceType);
                if (requestBody == null || requestBody.trim().isEmpty()) {
                    System.out.println("请求体为空，跳过此请求。cpxx_key: " + cpxxKey);
                    continue;
                }

                ResponseEntity<String> response = httpUtils.sendPostRequest(RAILWAY_API_URL, requestBody, ACCESS_CODE);

                System.out.println("响应状态: " + response.getStatusCode());
                System.out.println("响应体: " + response.getBody());

                recordUploadLog(cpxxKey, response.getStatusCode().is2xxSuccessful() ? "ok" : "error",
                        response.getStatusCodeValue(), response.getBody(), interfaceType);
            }
        } catch (Exception e) {
            System.err.println("发生异常: " + e.getMessage());
            throw new RuntimeException("查询和上传失败", e);
        }
    }

    // 检查是否已上传数据
    private boolean checkIfUploaded(long cpxxKey, String interfaceType) {
        LambdaQueryWrapper<DataUploadLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DataUploadLog::getCpxxKey, cpxxKey);
        queryWrapper.eq(DataUploadLog::getInterfaceType, interfaceType);
        return dataUploadLogMapper.selectCount(queryWrapper) > 0;
    }

    // 记录上传日志到数据库
    private void recordUploadLog(long cpxxKey, String uploadStatus, int responseCode, String responseMessage, String interfaceType) {
        DataUploadLog log = new DataUploadLog();
        log.setCpxxKey(cpxxKey);
        log.setUploadTime(java.sql.Timestamp.valueOf(LocalDateTime.now()));
        log.setUploadStatus(uploadStatus);
        log.setResponseCode(responseCode);
        log.setResponseMessage(responseMessage);
        log.setInterfaceType(interfaceType);
        log.setCreateTime(java.sql.Timestamp.valueOf(LocalDateTime.now()));
        log.setUpdateTime(java.sql.Timestamp.valueOf(LocalDateTime.now()));
        dataUploadLogMapper.insert(log);
    }



    // 根据铁路平台名称获取 cpxx_key 列表
    private List<Long> getCpxxKeysFromPlatformName(String railwayPlatformName) {
        return trainRepository.getCpxxKeysByRailwayPlatformName(railwayPlatformName);
    }

    // 构建运往地 API 的请求体
    private String buildRequestBody(String railwayPlatformName) {
        return "{\"accessCode\": \"" + ACCESS_CODE + "\"," +
                "\"railwayPlatformName\": \"" + railwayPlatformName + "\"}";
    }

    // 构建铁路信息 API 的请求体，使用 TrainInfo 数据（优先从 cpxxall 获取）
    @SneakyThrows
    private String buildRequestBody(CcxxallEntity ccxxall, TrainInfo cpxxall, String interfaceType) {
        // 创建对象映射器用于 JSON 序列化
        ObjectMapper mapper = new ObjectMapper();
        RailwayDataRequestBody requestBody = new RailwayDataRequestBody();

        // 构建装车开始时间 shipping_start_time (格式: yyyy-MM-dd HH:mm:ss)
        // 来源: ccxx_datestart (yyyyMMdd) 和 ccxx_timestart (HHmmss)
        String shippingStartTime = formatDateTime(String.valueOf(ccxxall.getCcxxDatestart()), ccxxall.getCcxxTimestart());

        // 构建装车结束时间 shipping_end_time (格式: yyyy-MM-dd HH:mm:ss)
        // 来源: ccxx_dateend (yyyyMMdd) 和 ccxx_timeend (HHmmss)
        String shippingEndTime = formatDateTime(ccxxall.getCcxxDateend(), ccxxall.getCcxxTimeend());

        // 获取当前时间 (格式: yyyy-MM-dd HH:mm:ss)
        // 用于设置 create_time 字段
        String currentTime = getCurrentTime();


        requestBody.setAccessCode(ACCESS_CODE);
        requestBody.setShippingName("国网能源哈密煤电大南湖二号露天煤矿");
        // 设置平台名称.固定值，表示装车平台
        requestBody.setPlatformName("巴特站");
        requestBody.setTakeName(ccxxall.getCcxxDaozh());// 设置收货单位名称ccxx_daozh (到达站名称)
        requestBody.setTrainNumber(ccxxall.getCcxxCheci().split("\\.")[0]);// 设置车次号ccxx_checi (车次号)，去除小数点后部分
        requestBody.setCompartNum(ccxxall.getCcxxZcps().intValue());// 设置车厢总数ccxx_zcps (总车厢数)
        requestBody.setTonnage(String.valueOf(ccxxall.getCcxxZshizh()));// 设置吨数
        requestBody.setShippingStartTime(shippingStartTime);// 设置装车开始时间shippingStartTime (由 ccxx_datestart 和 ccxx_timestart 组合)
        requestBody.setShippingEndTime(shippingEndTime);// 设置装车结束时间shippingEndTime (由 ccxx_dateend 和 ccxx_timeend 组合)
        requestBody.setTotalMaxWeight(ccxxall.getCcxxZzaizh());//
        String destinationName = ccxxall.getCcxxDaozh(); // 设置目的地信息ccxx_daozh (到达站名称)
        Destination matchedDestination = findMatchingDestination(destinationName);
        if (matchedDestination != null) {
            requestBody.setDestinationId(matchedDestination.getId());// 设置目的地id
            requestBody.setDestinationName(matchedDestination.getRailwayPlatformName());// 设置目的地名称
        } else {
            // 未找到匹配目的地时，使用默认值
            log.warn("未找到匹配的目的地: " + destinationName + "，使用默认值");
            requestBody.setDestinationId("0");
            requestBody.setDestinationName(destinationName);
        }
        requestBody.setProductId("0");

        // 设置煤种名称ccxx_pinzh (煤种名称)
        String productName = ccxxall.getCcxxPinzh();
        if (productName != null) {
            requestBody.setProductName(ccxxall.getCcxxPinzh());
        }else {
            requestBody.setProductName("0");
        }
        RailwayDetails details = new RailwayDetails();//子表
        // 设置车型cpxx_chexing (车型名称)
        details.setType(cpxxall.getCpxxChexing());
        details.setNo(String.valueOf(cpxxall.getCpxxChehao()));// 设置车号cpxx_chehao (车号)
        details.setMaxWeight(ccxxall.getCcxxZzaizh());// 设置车厢最大载重compartTonnage (总载重 / 车厢数)
        details.setTrainEmpty(getTrainEmptyStatus(ccxxall.getCcxxZshizh()));// 设置是否空车ccxx_zshizh (总实装)，0 表示空车，>0 表示重车
        details.setNetWeight(String.valueOf(cpxxall.getCpxxCheshizh()));// 设置净重cpxx_cheshizh (车实重)
        details.setProductName(cpxxall.getCpxxChepinzh());// 设置产品名称,cpxx_chepinzh (车品种名称)
        details.setDelFlag("0");// 设置删除标志.0 表示未删除

        // 设置详情中的目的地信息
        if (matchedDestination != null) {
            // 设置目的地 ID
            details.setDestinationId(matchedDestination.getId());
            // 设置目的地名称
            details.setDestinationName(matchedDestination.getRailwayPlatformName());
        } else {
            // 未找到匹配目的地时，使用默认值
            details.setDestinationId("1892437775448154114");
            details.setDestinationName(destinationName);
        }

        requestBody.setRailwayDetailsList(Arrays.asList(details));

        // 设置创建时间,当前系统时间
        requestBody.setCreate_time(currentTime);

        // 设置接口类型,interfaceType
        requestBody.setInterfaceType(interfaceType);

        return mapper.writeValueAsString(requestBody);
    }

    private String formatDateTime(String date, String time) {
        // 检查输入是否有效
        if (date == null || time == null || date.length() != 8 || time.length() != 6) {
            throw new IllegalArgumentException("年月日不是8位或者时分秒不是6位");
        }
        // 从 date 中提取年、月、日
        String year = date.substring(0, 4);
        String month = date.substring(4, 6);
        String day = date.substring(6, 8);
        // 从 time 中提取时、分、秒
        String hour = time.substring(0, 2);
        String minute = time.substring(2, 4);
        String second = time.substring(4, 6);

        // 组合成 yyyy-MM-dd HH:mm:ss 格式
        return String.format("%s-%s-%s %s:%s:%s", year, month, day, hour, minute, second);
    }

    private String getCurrentTime() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return LocalDateTime.now().format(formatter);
    }

    // 判断是否空车的方法
    private int getTrainEmptyStatus(Double ccxxZshizh) {
        if (ccxxZshizh == null) {
            return 0; // 当 ccxxZshizh 为 null 时，返回 0 表示空车
        }
        return ccxxZshizh > 0 ? 1 : 0; // 非 null 时，根据值判断是否为空车
    }

    private Destination findMatchingDestination(String destinationName) {
        List<Destination> destinations = DestinationInitializer.getDestinationList();
        if (destinations == null) {
            log.error("目的地列表未初始化");
            return null;
        }
        for (Destination dest : destinations) {
            if (dest.getRailwayPlatformName().equals(destinationName)) {
                return dest;
            }
        }
        return null;
    }

    @Override
    public void checkTwoMonthDataAndCallApi() {
        log.info("【两个月数据上传任务】开始执行...");

        List<CcxxallEntity> ccxxallList = ccxxallMapper.selectList(
                new QueryWrapper<CcxxallEntity>().between("ccxx_dateend",
                        LocalDate.now().minusMonths(2).format(DateTimeFormatter.ofPattern("yyyyMMdd")),
                        LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                )
        );

        for (CcxxallEntity ccxxall : ccxxallList) {
            Integer ccxxKey = ccxxall.getCcxxKey();
            // 改成这样 → 正确
            String ccxxPici = ccxxall.getCcxxPici();

            TrainInfo cpxxall = trainInfoMapper.selectOne(
                    new QueryWrapper<TrainInfo>().eq("cpxx_pici", ccxxPici).last("LIMIT 1")
            );
            if (cpxxall == null) {
                log.warn("未找到对应 cpxx_key，跳过 ccxx_key: {}", ccxxKey);
                continue;
            }

            String interfaceType = "receiveRailwayAndDetailsInfo";
            long cpxxKey = cpxxall.getCpxxKey().longValue();

            if (checkIfUploaded(cpxxKey, interfaceType)) {
                log.info("数据已上传，跳过 cpxx_key: {}", cpxxKey);
                continue;
            }

            String requestBody = buildRequestBody(ccxxall, cpxxall, interfaceType);
            if (requestBody == null || requestBody.trim().isEmpty()) {
                log.warn("请求体为空，跳过 cpxx_key: {}", cpxxKey);
                continue;
            }

            ResponseEntity<String> response = httpUtils.sendPostRequest(RAILWAY_API_URL, requestBody, ACCESS_CODE);
            log.info("响应状态: {}", response.getStatusCode());
            log.info("响应体: {}", response.getBody());

            recordUploadLog(cpxxKey, response.getStatusCode().is2xxSuccessful() ? "ok" : "error",
                    response.getStatusCodeValue(), response.getBody(), interfaceType);
        }

        log.info("【两个月数据上传任务】执行完成！");
    }

}